class Mobile::NewsController < ApplicationController

  layout "mobile/list"

  def index
    get_public_var

    condition = {}
    if @important
      condition = {is_important_news: @important} 
    elsif @category_id.present?
      condition={category_id: get_categories}
    elsif params["sptitle_id"].present?
      condition = {id: get_sptitles}
    end
    meiti = Category.where(:cataname => '媒体华理').first
    if @category_id.present? &&  @category_id.to_i == meiti.id
      @news = News.where(:category_id => meiti.id).order("created_at desc").page params[:page]
    else
      @news = News.index_news.where(condition).order("ordinal desc").order("created_at desc").page params[:page]
    end
  end

  def show
    get_public_var
    
    @news = News.where({id: params[:id]}).first
    if @news
      @news.update_attributes(hits: 1) if @news.hits.blank?
      sql = "update news set hits = hits+1 where id=#{@news.id}"
      ActiveRecord::Base.connection.execute(sql)
    else
      flash[:error]='帖子不存在'
      redirect_to '/mobile'
    end

  end

  private
  def get_public_var
    @important = params["important"]
    @category_id = params["category_id"]
    @sptitle_id = params["sptitle_id"]    
    @category = Category.where(id: @category_id).last
  end

  def get_categories
    categories = Array.new()
    categories << @category.id
    tmp_categories = NewsHelper::CATEGORY_HASH_ARRAY[@category.id.to_s]
    categories << tmp_categories if tmp_categories.present?
    categories.each do |category_array|
      if category_array.class == Array
        category_array.each do |category_id|
          category = Category.find category_id
          categories << category_id
          category_children = category.children.collect(&:id)
          categories << category_children if category_children.present? 
        end
      elsif category_array.class == Fixnum
        category = Category.find category_array
        category_children = category.children.collect(&:id)
        categories << category_children if category_children.present? 
      end
    end
    categories
  end

  def get_sptitles
    @sptitle = Sptitle.find(params["sptitle_id"])
    ids = NewsSptitle.where(sptitle_id: @sptitle.id).collect(&:news_id)    
  end

end